package www.openteam.com.ui.business;


import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import www.openteam.com.R;
import www.openteam.com.adapter.DeliverNoteAdp;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.DlryNtPrimaryTable;
import www.openteam.com.bean.DlryNtSublist;
import www.openteam.com.bean.InsertStatus;
import www.openteam.com.bean.ShowSignature;
import www.openteam.com.contract.business.DlryNoteContract;
import www.openteam.com.presenter.business.DeliveryNotePresenter;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.view.DialogUtil;
import www.openteam.com.view.SignatureView;


/**
 * A simple {@link Fragment} subclass.
 */
public class DeliverNoteFragment extends mBaseFragment<DeliveryNotePresenter>
        implements DlryNoteContract.DlryNoteView {


    @Bind(R.id.dlry_note_serchview)
    SearchView dlryNoteSerchview;
    @Bind(R.id.dlry_note_scan)
    AppCompatImageView dlryNoteScan;
    @Bind(R.id.dlry_recycleView)
    RecyclerView dlryRecycleView;
    @Bind(R.id.dlry_note_number)
    TextView dlryNoteNumber;
    @Bind(R.id.dlry_note_man)
    TextView dlryNoteMan;
    @Bind(R.id.dlry_note_date)
    TextView dlryNoteDate;
    @Bind(R.id.dlry_note_address)
    TextView dlryNoteAddress;
    @Bind(R.id.dlry_note_short)
    TextView dlryNoteShort;
    @Bind(R.id.dlry_note_tolmonery)
    TextView dlryNoteTolmonery;
    @Bind(R.id.return_confirmation)
    Button returnConfirmation;
    @Bind(R.id.showSignture)
    Button showSignature;
    private int RESULT = 1;
    private String dCode = "";
    private SignatureView signatureView;
    private String primaryID = "";
    private String TAG = getClass().getSimpleName();
    private int returnStatus = -1;
    String checker;
    String checkDate;
    private AlertDialog alertDialog;
    private ImageView signature;
    private String path;
    private DialogUtil dialogUtil;

    public DeliverNoteFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_deliver_note, container, false);
        ButterKnife.bind(this, view);
        mPresenter = loadPresenter();
        initData();
        initView();
        initListener();
        return view;

    }

    protected void initData() {
        if (mPresenter != null)
            mPresenter.attachView(this);
        dlryRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        mProgressDialog = new ProgressDialog(getContext());
        checker = mySetting.getString("mName", "");
        checkDate = getCurrentTime();
        dialogUtil = new DialogUtil();
    }

    protected void initListener() {
        dlryNoteScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ScanActivity.class);
                startActivityForResult(intent, RESULT);
            }
        });
        dlryNoteSerchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
//                Log.e(TAG, "onQueryTextSubmit: stype" + stype + "--rdson" + query);
//                query = "OTZOSE190700001";
                Log.e(TAG, "onQueryTextSubmit: " + query);
                dCode = query;
                mPresenter.getPrimaryData(query);
                mPresenter.getSublistData(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String work_order_id = data.getStringExtra("work_order_id");
        dCode = work_order_id;
        Log.e(TAG, "onActivityResult: " + dCode);
        if (requestCode == RESULT && !work_order_id.equals("")) {
            dlryNoteSerchview.setQuery(work_order_id, true);
        }

    }


    protected void initView() {
        dlryNoteSerchview.setSubmitButtonEnabled(true);
        dlryNoteSerchview.onActionViewExpanded();
    }


    @Override
    protected DeliveryNotePresenter loadPresenter() {
        return new DeliveryNotePresenter();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void getPrimaryData(DlryNtPrimaryTable dlryNtPrimaryTable) {
        DlryNtPrimaryTable.DataBeanX.DataBean dataBean = dlryNtPrimaryTable.getData().getData().get(0);
        dlryNoteNumber.setText(dataBean.getRdsno());
        dlryNoteMan.setText(dataBean.getSender());
        dlryNoteDate.setText(dataBean.getSenddate());
        dlryNoteShort.setText(dataBean.getShortname());
        dlryNoteTolmonery.setText(cleanDecimal(dataBean.getTolmoney()));
        dlryNoteAddress.setText(dataBean.getSendaddress());
        primaryID = dataBean.getId();
        returnStatus = dataBean.getReturnStatus();
        //returnConfirmation.setClickable(true);
        if (returnStatus == 1) {//该单已经确认回单
            returnConfirmation.setText("取消回单");
            showSignature.setText("显示签名");
            showSignature.setClickable(true);
        } else if (returnStatus == 0) {//该单还未进行回单确认
            returnConfirmation.setText("确认回单");
            showSignature.setText("暂无签名");
            showSignature.setClickable(false);

        }
    }

    public String cleanDecimal(String text) {
        Double num = Double.valueOf(text.isEmpty() ? "0" : text);
        NumberFormat nf = NumberFormat.getInstance();
        return nf.format(num);
    }

    @Override
    public void getPrimaryDataFail(String msg) {
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void getSublistData(DlryNtSublist dlryNtSublist) {
        DeliverNoteAdp deliverNoteAdp = new DeliverNoteAdp(getContext(), dlryNtSublist.getData().getData());
        dlryRecycleView.setAdapter(deliverNoteAdp);
    }

    @Override
    public void getSublistFail(String msg) {
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void postPicSuccess(InsertStatus insertStatus) {
        ToastUtil.showToast(getContext(), "提交成功");
//        alertDialog.cancel();
        mPresenter.getPrimaryData(dCode);
        mPresenter.getSublistData(dCode);
    }

    @Override
    public void postPicFail(String Msg) {
        ToastUtil.showToast(getContext(), Msg);
    }

    @Override
    public void cancleRcpSuccess(InsertStatus insertStatus) {
        ToastUtil.showToast(getContext(), "取消成功");
        mPresenter.getPrimaryData(dCode);
        mPresenter.getSublistData(dCode);
        //signature/20190806141842_1565072318169.png
    }

    @Override
    public void cancleRcpFail(String Msg) {
        ToastUtil.showToast(getContext(), Msg);
    }

    @Override
    public void showSignature(ShowSignature showSignature) {
        String nSignature = showSignature.getData().getData().get(0).getNSignature();
        path = nSignature.substring(2);
        downLoadImage("http://sz-openteam.iask.in:16371/" + path).subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<byte[]>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onNext(byte[] bytes) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);//实际情况应该做图片处理，避免oom
                Log.e(TAG, "getByteCount: " + bitmap.getByteCount());
                Matrix matrix = new Matrix();
                matrix.setScale(0.8f, 0.8f);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                        bitmap.getHeight(), matrix, true);
//                Log.i(TAG, "压缩后图片的大小" + (bitmap.getByteCount() / 1024 / 1024)
//                        + "M宽度为" + bitmap.getWidth() + "高度为" + bitmap.getHeight());
                signature.setImageBitmap(bitmap);
            }
        });
    }

    @Override
    public void showgetSignatureFail(String msg) {
        ToastUtil.showToast(getContext(), msg);
    }

    @OnClick({R.id.showSignture, R.id.return_confirmation})
    public void onViewClicked(View view) {
        if (returnStatus == -1) {
            ToastUtil.showToast(getContext(), "当前没有要操作的单据");
            return;
        }
        switch (view.getId()) {
            case R.id.showSignture:
                setDialog("showSignture");
                break;
            case R.id.return_confirmation:
                if (returnStatus == 1) {//进行回单取消
                    dialogUtil.show(getContext(), "该操作会删除已有签名！"+"\n"+"是否确认修改", new DialogUtil.DialogButtonListener() {
                        @Override
                        public void sure() {
                            mPresenter.cancleRecipe(primaryID);
                        }

                        @Override
                        public void cancel() {

                        }
                    });

                } else {
                    setDialog("return_confirmation");
                }
                break;
        }
    }


    private void setDialog(String type) {
        View dialog = null;
        if (type.equals("return_confirmation")) {
            dialog = getActivity().getLayoutInflater().inflate(R.layout.item_dlry_signature,
                    null);
            signatureView = (SignatureView) dialog.findViewById(R.id.signatureView);//签名区
            AppCompatButton clear = (AppCompatButton) dialog.findViewById(R.id.clear);//清除
            AppCompatButton retrateclear = (AppCompatButton) dialog.findViewById(R.id.retrate);//后退
            AppCompatButton advance = (AppCompatButton) dialog.findViewById(R.id.advance);//前进;
//            AppCompatButton save = (AppCompatButton) dialog.findViewById(R.id.save);//保存;
            clear.setOnClickListener(this);
            retrateclear.setOnClickListener(this);
            advance.setOnClickListener(this);
//            save.setOnClickListener(this);
        } else if (type.equals("showSignture")) {
            mPresenter.showSignature(primaryID);
            dialog = getActivity().getLayoutInflater().inflate(R.layout.dialog_showsignature,
                    null);
            signature = (ImageView) dialog.findViewById(R.id.signature);//签名

        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setPositiveButton(getResources().getString(R.string.queding), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                try {
                    if (null!=signatureView){//进行签名
                        if (signatureView.isSign()) {
                            File file = signatureView.save("");
                            mPresenter.postPicture(file, primaryID, checker, checkDate, "1");
                        }
                        signatureView.clear();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.quxiao), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setView(dialog);
        alertDialog = builder.create();
        alertDialog.show();
    }

    @Override
    protected void otherViewClick(View view) {
        switch (view.getId()) {
            case R.id.clear:
                signatureView.clear();
                break;
            case R.id.retrate:
                signatureView.goForward();
                break;
            case R.id.advance:
                signatureView.goBack();
                break;
//            case R.id.save:
//                try {
//                    if (!signatureView.isSign()){
//                        File file = signatureView.save("");
//
////                    uploadMultiFile(file,primaryID,checker,checkDate,"1");
//                        mPresenter.postPicture(file, primaryID, checker, checkDate, "1");
//                    }
//                    signatureView.clear();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                break;
        }
    }

    private void uploadMultiFile(File file, String zbid, String returnMan, String returnDate, String returnStatus) {//将图片发送到服务器
        final String url = "http://sz-openteam.iask.in:16371/index.php/OpenTeam/DlryNote/postSignture";

        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image1", file.getName(), fileBody)
                .addFormDataPart("zbid", zbid)
                .addFormDataPart("returnMan", zbid)
                .addFormDataPart("$returnDate", zbid)
                .addFormDataPart("$returnStatus", zbid)
//                .addFormDataPart("image2", "yyw.jpg", fileBody2)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = httpBuilder
                //设置超时
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.e("aa", "uploadMultiFile() e=" + e);
                ToastUtil.showToast(getContext(), "提交失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Log.i("bb", "uploadMultiFile() response=" + response.body().string());
                ToastUtil.showToast(getContext(), "提交成功");

            }
        });
    }

    public String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date).toString();

    }

    public static Bitmap getImage(String path) {

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            System.out.println("tdw1");
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Observable<byte[]> downLoadImage(final String path) {
        Log.e(TAG, "downLoadImage: " + path);
        return Observable.create(new Observable.OnSubscribe<byte[]>() {
            @Override
            public void call(final Subscriber<? super byte[]> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    //访问网络操作
                    Request request = new Request.Builder().url(path).build();
                    OkHttpClient client = new OkHttpClient();
                    ;
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                byte[] data = response.body().bytes();
                                if (data != null) {
                                    subscriber.onNext(data);
                                }
                            }
                            subscriber.onCompleted();
                        }
                    });

                }
            }
        });

    }

}
